#!/usr/bin/env python3
# set coding: utf-8
"""
@Project : litewaf2
@File :    models.py
@Time :    2023/2/21 14:28
@Author :  richard zhu
@Email :   gaotao.zhugt@dtzhejiang.com
@purpose : 
"""
from django.db import models
import json

class BaseModel(models.Model):
    gmt_create = models.DateTimeField('创建时间,自动创建', auto_now_add=True, null=True, help_text='创建时间')
    # 使用save可以达到自动更新的效果，使用update不会自动更新，因此需要携带上这个字段
    gmt_modify = models.DateTimeField('更新时间,自动更新', auto_now=True, null=True, help_text='更新时间')
    status = models.BooleanField(default=True)

    def to_dict(self, values=[]):
        fields = []
        for field in self._meta.fields:
            if values:
                if field.name in values:
                    fields.append(field.name)
            else:
                fields.append(field.name)

        dict_result = {}
        import datetime
        for attr in fields:
            if isinstance(getattr(self, attr), datetime.datetime):
                dict_result[attr] = getattr(self, attr).strftime('%Y-%m-%d %H:%M:%S')
            elif isinstance(getattr(self, attr), datetime.date):
                dict_result[attr] = getattr(self, attr).strftime('%Y-%m-%d')
            else:
                dict_result[attr] = getattr(self, attr)
        return dict_result

    def to_str(self, **kwargs):
        return json.dumps(self.to_dict(**kwargs))

    class Meta:
        abstract = True

class SysLog(BaseModel):
    """
    记录用户行为
    限制登陆
    """
    ACTION_CHOICE=(
        ('create', '创建'),
        ('update', '更新'),
        ('delete', '删除'),
    )

    ATTR_CHOICE = (
        ('Login', '登陆'),
        ('ItemGroup', '密码组'),
        ('Item', '密码条'),
        ('Fields', '字段')
    )

    user = models.CharField(max_length=150)
    ip = models.GenericIPAddressField()
    action = models.CharField(max_length=50, choices=ACTION_CHOICE, verbose_name="动作", default=1)
    attr = models.CharField(max_length=120, choices=ATTR_CHOICE, verbose_name="属性", blank=True, null=True)
    message = models.TextField(verbose_name="信息", blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")

    def __str__(self):
        return "<%s> [%s] [%s] from <%s>" % (self.user, self.action, self.message, self.ip)

    class Meta:
        verbose_name = "用户行为记录"
        verbose_name_plural = "用户行为记录"
        ordering = ['-created_at']